from typing import Optional
from PySide6.QtCore import QObject, QThread, qDebug, Signal, QTimer
from Libs.Backend.Api import Api
import math, time
from . import *


class BackendApiThread(QObject):
    finished = Signal()
    loginResp = Signal(dict)
    downloadDarenInfoResp = Signal(dict)
    uploadDarenInfoResp = Signal(dict)
    updateDarenInfoResp = Signal(dict)

    def __init__(self, parent=None, *args, **kwargs):
        super(BackendApiThread, self).__init__(parent)
        self.cookies = kwargs.get('cookies', '')
        self.darens = kwargs.get('darens', {})
        self.downloadBody = kwargs.get('downloadBody', {})
        self.header = kwargs.get('header', {})
        self.api = None

    def initBackendApi(self):
        self.api = Api(header=self.header, cookie=self.cookies, api=self.api)

    def quit(self):
        self.finished.emit()

    def downloadDarenContactList(self):
        qDebug(f'BackendApiThread running(download daren contact list)')
        if not self.api or isinstance(self.api, Api):
            self.initBackendApi()
        self.api.body = self.downloadBody

        res = self.api.downloadDarenInfo()
        logging.info(f'resresres: {res}')
        self.downloadDarenInfoResp.emit({'data': res.get('data', [])})
        self.finished.emit()

    def downloadDarenInfo(self):
        """
        启动获取达人联系方式线程
        """
        qDebug(f'BackendApiThread running(download daren infos)')
        if not self.api or isinstance(self.api, Api):
            self.initBackendApi()
            
        page, pages = 1, 1
        while pages >= page:
            self.api.body = {
                'page': page, 'page_size': 10, 'sort': 'desc', 'order': 'id',
                'start_date': self.downloadBody.get('start_date', 0),
                'end_date': self.downloadBody.get('end_date', 0),
                'contact_mode': self.downloadBody.get('contact_mode', 0),
            }

            res = self.api.downloadDarenInfo()
            logging.info(f'resresres: {res}')
            if not res:
                self.downloadDarenInfoResp.emit({'data': [], 'progress': 0.0})
                break
            pages = res.get('pages', pages)
            data = res.get('data', [])
            logging.debug(f'pages: {pages} - {page}')
            if not data:
                logging.debug(f'not data: {pages} - {page}')
                break
            self.downloadDarenInfoResp.emit({'data': data, 'progress': round(page / pages, 2) * 100})
            page += 1
            logging.debug(f'running: {pages} - {page} - {page >= pages}')
            
        logging.debug(f'done: {pages} - {page} - {page >= pages}')
        self.finished.emit()

    def uploadDarenInfo(self):
        """
        开启上传达人信息接口线程
        """
        qDebug(f'BackendApiThread running(upload daren infos)')
        data = []
        if not self.api or isinstance(self.api, Api):
            self.initBackendApi()
        logging.debug(f'uploadDarenInfo: {self.darens}')
        for uid, daren in self.darens.items():
            self.api.body = daren
            uploadRes = self.api.uploadDarenInfo()
            # self.uploadDarenInfoResp.emit({'uid': uid, 'res': uploadRes, 'id': uploadRes})
            ret = {'uid': uid}
            if not uploadRes:
                self.uploadDarenInfoResp.emit(ret)
            else:
                ret.update(uploadRes)
                self.uploadDarenInfoResp.emit(ret)
            time.sleep(3.0)
        self.finished.emit()

    def updateDarenInfo(self):
        """
        开启上传修改达人信息接口线程
        """
        qDebug(f'BackendApiThread running(update daren infos)')
        data = []
        if not self.api or isinstance(self.api, Api):
            self.initBackendApi()
        logging.debug(f'updateDarenInfo: {self.darens}')
        for uid, daren in self.darens.items():
            self.api.id = daren.get('id', 0)
            # mobile = daren.get('mobile', '')
            # wechat = daren.get('wechat', '')
            # if not wechat and not mobile:
            #     continue

            # self.api.body = {
            #     'mobile': mobile,
            #     'wechat': wechat,
            #     'dy_id': daren.get('dy_id', ''),
            # }
            
            self.api.body = {}
            if daren.get('mobile', ''):
                self.api.body['mobile'] = daren.get('mobile', '')
            if daren.get('wechat', ''):
                self.api.body['wechat'] = daren.get('wechat', '')
            if daren.get('nickname', ''):
                self.api.body['nickname'] = daren.get('nickname', '')
            if daren.get('level', 0):
                self.api.body['level'] = daren.get('level', 0)
            if daren.get('fans_num', 0):
                self.api.body['fans_num'] = daren.get('fans_num', 0)

            uploadRes = self.api.updateDarenInfo()
            self.updateDarenInfoResp.emit({'uid': uid, 'res': uploadRes, 'id': uploadRes})
            time.sleep(1.0)
        self.finished.emit()

    def login(self):
        """
        开启登陆后台接口线程
        """
        qDebug(f'BackendApiThread running(login)')
        data = []
        if not self.api or isinstance(self.api, Api):
            self.initBackendApi()
        self.api.body = {
            'mobile': '13333333333',
            'password': 'Aa123456'
        }
        data = self.api.login()
        self.loginResp.emit(data)
        self.finished.emit()

    
